<template>
    <a-spin :spinning="confirmLoading">
      <j-form-container :disabled="formDisabled">
        <a-form-model :model="form" slot="detail" :rules="rules" ref="villageIndustryForm">
           <a-row :gutter="24">
             <a-col :span="4">
              <a-form-model-item 
              class="formitem"
                :colon="false"
                label="年份" 
                prop="year"
                :rules="{
                    required: true,
                    message: '请选择年份',
                    trigger: 'change',
                }"
                >
                  <a-date-picker
                       :disabled="isShow"
                      style="width:170px;margin-top:20px"
                      :allowClear="false"
                      placeholder="请选择年份"
                      format="YYYY"
                      mode="year"
                      :value="year"
                      :open="open"
                      @openChange="openChange"
                      @panelChange="panelChange"
                  />
              </a-form-model-item>
             </a-col>
            <a-col :span="20">
            <div class="title-total" style="height:60px">
              <template v-for="(item,index) in columns">
                <div :style="{width:item.width,height:'60px',textAlign:item.align}"  :key="index">
                    {{item.value}}
                </div>
              </template>
              </div>
              <a-table :data-source="form.tableList" :pagination="false" :scroll={y:400}  row-key="id" class="my-table">
                  <a-table-column dataIndex="burgName" key="burgName" title="行政区划" :width="90">
                      <template slot-scope="text, record">
                          {{record.burgName}}
                      </template>
                  </a-table-column>
                  <a-table-column dataIndex="plantArea" key="plantArea" title="种植面积（亩）" :width="130">
                      <template slot-scope="text, record,index">
                      <a-form-model-item 
                         :prop=" 'tableList.' + index + '.plantArea' "
                         :rules="[{validator:handlePlantNumCheck}]"
                      >
                      <a-input-number
                          :disabled="isShow"
                          v-model="record.plantArea"
                          placeholder="请输入"
                      />
                      </a-form-model-item>
                      </template>
                  </a-table-column>
                  <a-table-column dataIndex="fruitsOutput" key="fruitsOutput" title="鲜果产量(吨)" :width="145">
                      <template slot-scope="text, record,index">
                      <a-form-model-item 
                       :rules="[{validator:handlePlantNumCheck1}]"
                        :prop=" 'tableList.' + index + '.fruitsOutput' "
                      >
                      <a-input-number
                           :disabled="isShow"
                          v-model="record.fruitsOutput"
                          placeholder="请输入"
                      />
                      </a-form-model-item>
                      </template>
                  </a-table-column>
                  <a-table-column dataIndex="industryProduction" key="industryProduction" title="产业产值(万元)" :width="130">
                      <template slot-scope="text, record,index">
                      <a-form-model-item 
                       :rules="[{validator:handlePlantNumCheck}]"
                        :prop=" 'tableList.' + index + '.industryProduction' "
                      >
                      <a-input-number
                          :disabled="isShow"
                          v-model="record.industryProduction"
                          placeholder="请输入"
                      />
                      </a-form-model-item>
                      </template>
                  </a-table-column>
                  <a-table-column dataIndex="plantGarden" key="plantGarden" title="种植果园树(个)" :width="130">
                      <template slot-scope="text, record,index">
                      <a-form-model-item 
                       :rules="[{validator:handlePlantNumCheck}]"
                        :prop=" 'tableList.' + index + '.plantGarden' "
                      >
                      <a-input-number
                          :disabled="isShow"
                          v-model="record.plantGarden"
                          placeholder="请输入"
                      />
                      </a-form-model-item>
                      </template>
                  </a-table-column>
                  <a-table-column dataIndex="plantPeople" key="plantPeople" title="种植户人数(人)" :width="140">
                      <template slot-scope="text, record,index">
                      <a-form-model-item 
                       :rules="[{validator:handlePlantNumCheck}]"
                        :prop=" 'tableList.' + index + '.plantPeople' "
                      >
                      <a-input-number
                           :disabled="isShow"
                          v-model="record.plantPeople"
                          placeholder="请输入"
                      />
                      </a-form-model-item>
                      </template>
                  </a-table-column>
                  <a-table-column dataIndex="company" key="company" title="生产加工企业(家)" :width="140">
                      <template slot-scope="text, record,index">
                      <a-form-model-item 
                       :rules="[{validator:handlePlantNumCheck}]"
                        :prop=" 'tableList.' + index + '.company' "
                      >
                      <a-input-number
                           :disabled="isShow"
                          v-model="record.company"
                          placeholder="请输入"
                      />
                      </a-form-model-item>
                      </template>
                  </a-table-column>
              </a-table>
            </a-col>
          </a-row>
        </a-form-model>
      </j-form-container>
    </a-spin>
</template>

<script>
  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import JMultiSelectTag from "@/components/dict/JMultiSelectTag"
  import {dpVillagequeryDetailBYear,dpVillagequeryBurgList} from '@/api/dashboardPaltform'
  import moment from 'moment'
  export default {
    name: 'TxppServiceItemsForm',
    components: {
      JFormContainer,
      JDictSelectTag,
      JMultiSelectTag,
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      //详情
      isShow: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        oldYear:'',
        isAdd:true,
        varietyOptions:[],
        year:'',
        open:false,
        result:{},
        userId:'',
        seePassword:true,
        positionList:[],
        tqppSystemList:[],//权限列表
        columns: [
            { title: '行政区规划', dataIndex: '塘栖镇',width:'55px',value:'塘栖镇',align:'center'},
            { title: '种植面积(亩)', dataIndex: 'plantArea',width:'177px',value:0 ,align:'center'},
            { title: '鲜果产量(吨)', dataIndex: 'fruitsOutput',width:'177px',value:0 ,align:'center'},
            { title: '产业产值(万元)', dataIndex: 'industryProduction',width:'177px',value:0 ,align:'center' },
            { title: '种植果园树(个)', dataIndex: 'plantGarden',width:'177px',value:0 ,align:'center' },
            { title: '种植户人数(人)', dataIndex: 'plantPeople' ,width:'177px',value:0 ,align:'center'},
            { title: '生产加工企业(家)', dataIndex: 'company',width:'177px',value:0 ,align:'center' },
        ], 
        form:{
            year:'',
        tableList: [],
        },
        model: {},
        labelCol: {
          xs: { span: 3 },
          sm: { span: 2 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 10 },
        },
        confirmLoading: false,
        rules: {},
        url: {
          add: "/plantGeneral/add",
          edit: "/plantGeneral/update",
          queryById: "/plantGeneral/queryDetailBYear"
        }
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    watch: {
      'form.tableList': {
        immediate: true,
        deep:true,
        handler(val) {
            let table = JSON.parse(JSON.stringify(val))
            table.map(item=>{
              if(!item.plantArea){
                item.plantArea = 0
              }
              if(!item.fruitsOutput){
                item.fruitsOutput = 0
              }
              if(!item.industryProduction){
                item.industryProduction = 0
              }
              if(!item.plantGarden){
                item.plantGarden = 0
              }
              if(!item.plantPeople){
                item.plantPeople = 0
              }
              if(!item.company){
                item.company = 0
              }
            })
            this.columns[1].value =  table.reduce((c, i) => c + i.plantArea * 1, 0)
            this.columns[2].value =  table.reduce((c, i) => c + i.fruitsOutput * 1, 0)
            this.columns[3].value =  table.reduce((c, i) => c + i.industryProduction * 1, 0)
            this.columns[4].value =  table.reduce((c, i) => c + i.plantGarden * 1, 0)
            this.columns[5].value =  table.reduce((c, i) => c + i.plantPeople * 1, 0)
            this.columns[6].value =  table.reduce((c, i) => c + i.company * 1, 0)
        }
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    mounted () {
    },
    methods: {
     handlePlantNumCheck(rule,value,callback){
        if (!value || new RegExp(/^[0-9]*[1-9][0-9]*$/).test(value)){
          callback();
        }else{
          callback("仅可输入整数!");
        }
      },
     handlePlantNumCheck1(rule,value,callback){
        if (!value || new RegExp(/^\d+(\.\d{1,2})?$/).test(value)){
          callback();
        }else{
          callback("最多保留两位小数!");
        }
      },
      openChange(status) {
        if (status) {
          this.open = true;
        } else {
          this.open = false;
        }
      },
      panelChange(value){
          const yearEnd = moment().endOf('year'); 
          if(value > yearEnd){
            return  this.$message.error('不能大于当前年份')
          }
          this.year = value.toString().substring(11, 15)
          this.form.year = this.year
          this.open = false;
      },
      add() {
        this.isAdd = true
        this.edit({},true)
      },
      //编辑
       async dpVillagequeryDetailBYear(val) {
            let res = await dpVillagequeryDetailBYear({year:val})
            if(res.success){
               this.result = res.result
               this.form.tableList = res.result
               this.result.map(item=>{
                   if(item.year){
                     this.year = moment(item.year,'YYYY')
                   }
               })
            }else{
              this.$message.error(res.message)
            }
        },
      //新增
       async dpVillagequeryBurgList(val) {
            let res = await dpVillagequeryBurgList()
            if(res.success){
               this.result = res.result
               this.form.tableList = res.result
            }else{
              this.$message.error(res.message)
            }
        },
        edit(record,show) {
            this.$nextTick(()=>{
                this.$refs.villageIndustryForm.resetFields()
            })
            if(!show){
                this.dpVillagequeryDetailBYear(record.year).then(()=>{
                    this.oldYear = record.year
                    let obj = this.result
                    this.model = Object.assign([], obj)
                    this.visible = true
                    this.$nextTick(() => {
                        this.form.tableList = this.model
                        this.form.year = this.year
                        this.year = moment(this.year,'YYYY')
                });
                 this.isAdd = false
                })
            }else{
                this.form.year = ''
                this.year = ''
                this.dpVillagequeryBurgList().then(()=>{
                    let obj = this.result
                    this.model = Object.assign([], obj)
                    this.visible = true
                    this.$nextTick(() => {
                        this.form.tableList = this.model
                    });
                })
            }
        },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.id};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit(res.result,false);
            }
          });
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.villageIndustryForm.validate((valid) => {
              if (valid) {
                  that.confirmLoading = true;
                  let httpurl = '';
                  let method = 'post';
                  let formData 
                  if(this.isAdd){
                    httpurl+=this.url.add;
                    this.form.tableList.forEach(item=>{
                        item.burgId =item.id
                        item.year = this.form.year
                        delete item.burgCode
                        delete item.id
                        delete item.latitude
                        delete item.longitude
                        delete item.burgType
                    })
                    formData = this.form.tableList
                  }else{
                    formData = {}
                    this.form.tableList.map(item=>{
                        item.year = Number(this.form.year)
                    })
                    formData.oldYear = this.oldYear
                    formData.nowYear = Number(this.form.year)
                    formData.list = this.form.tableList
                    httpurl+=this.url.edit;
                  }
                  httpAction(httpurl,formData,method).then((res)=>{
                    if(res.success){
                      that.$message.success(res.message);
                      that.$emit('ok');
                    }else{
                      that.$message.warning(res.message);
                    }
                  }).finally(() => {
                    that.confirmLoading = false;
                  })
              }else{
                 console.log('error submit!!');
                 return false;
            }
        })
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,
          'year',
        ))
      },
    }
  }
</script>
<style lang="less" scoped>
.ant-calendar-picker{
    width: 250.44px;
}
.formitem{
    width: 100%;
    font-size: 16px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
    text-align: left;
    background: #fafafa;
    height: 54px;
    border-bottom: 1px solid #e8e8e8;
    margin-top: 30px;
    line-height: 54px;
    text-align: left;
    margin-left: 24px;

   /deep/ .form-item-control-wrapper{
      margin-top: 30px;
    }
}
.title-total{
  width:100%;
  padding: 0 16px;
  display: flex;
  align-items: center;
  position: relative;
  top: 105px;
  z-index: 1;
}
/deep/ .my-table {
  ::-webkit-scrollbar {
   height: 0;
 }
  margin-top: -30px;
.ant-table-body{
  margin-top: 60px;
}
}
/deep/.villageIndustryForm{

// .ant-table-tbody > tr::hover{
//     background: transparent !important;
// }
// .ant-table-tbody > tr > td {
//     border-bottom: none;
// }
// .ant-table-tbody .ant-table-row td {
//     padding-top: 5px !important;
//     padding-bottom: 5px !important;
// }
// .ant-table-thead{
//     display: none;
// }
}
.ant-checkbox-wrapper{
margin: 10px 0;
}
.ant-radio-group{
padding: 0 10px;
}
.ant-form-item-control{
  line-height: 0px!important
}
.ant-col-sm-5{
  width: 100px;
}
.projectstyle{
.ant-col-sm-16{
  width: 88%;
  .ant-form-item-control{
    .ant-form-item-children{
      >div{
        width: 95% !important;
      }
    }
  }
}
}
</style>